package cn.bdqn.controller.user;

import cn.bdqn.controller.Role.RoleController;
import cn.bdqn.dto.LoginDTO;
import cn.bdqn.dto.LoginUser;
import cn.bdqn.pojo.Role.SysUserRole;
import cn.bdqn.pojo.User.User;
import cn.bdqn.service.Role.RoleService;
import cn.bdqn.service.Role.User_RoleService;
import cn.bdqn.service.user.UserService;
import cn.bdqn.utils.Json;
import cn.bdqn.utils.RedisCache;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.DaoTemplate;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.style.StylerUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.text.ParseException;

import java.text.SimpleDateFormat;
import java.util.*;

import static cn.bdqn.utils.RedisConstants.LOGIN_USER_TOKEN;

@Slf4j
@RestController
@RequestMapping("/api/user")
@CrossOrigin()
public class UserController {
    Json json=null;
    @Autowired
    UserService service;

    @Autowired
    RoleController roleController;


    @Autowired
    RoleService roleService;

    @Autowired
    User_RoleService userRoleService;
    @Autowired
    private RedisCache redisCache;

    public static final String tokenId="TOKEN-USER-";

    /**
     *登录方法
     * @param user phone,password 必传
     * @return
     */
    @PostMapping("/login")
    public Json login(@RequestBody LoginDTO user){
        System.out.println(user);
        if (user.getPhone() == null){
            return Json.fall("数据为空");
        }
        return  service.login(user);
    }
    @PostMapping("/phoneLogin")
    public Json loginByPhone(String phone,String code){
        User user = service.loginByPhone(phone);
        return Json.ok(user);
    }

    /**
     *
     * 注册方法
     *
     * @param user
     * @return
     */
    @PostMapping("/registered")
    public Json insertUser(@RequestBody User user){
        Integer integer = service.insertUser(user);
        if(integer>0){
            json=new Json(200,"成功");

        }else {
            json=new Json(400,"失败");
        }
        return json;
    }

    /**
     *
     * 修改方法
     * @param user
     * @return
     */
    @PutMapping("/updateUser")
    public Json updateUser(@RequestBody User user){
        if (Objects.isNull(user)){
            return Json.fall("请输入正规的密码");
        }
        System.out.println(user);
        Integer integer = service.updateUser(user);
        if(integer>0){
            json=new Json(200,"成功");
        }else{
            json=new Json(400,"失败");
        }
        return json;
    }

    /**
     * 删除用户，用户删除成功时，删除中间表中的相关信息
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('user:management')")
    @DeleteMapping("/deleteUser")
    public Json deleteUser(Integer id,Integer state){
        Integer integer = service.deleteUser(id,state);
        if(integer>0){
            json=new Json(200,"成功");
        }else{
            json=new Json(400,"失败");
        }
        return json;
    }

    /**
     *
     * 根据id批量停用
     * @param ids
     * @return
     */
    @PreAuthorize("hasAuthority('user:management')")
    @DeleteMapping("/deleteUsers")
    public Json updateUsers(String ids){
        List<Integer> id=new ArrayList<>();
        String[] split = ids.split(",");
       for(int i=0;i<split.length;i++){
           id.add(Integer.valueOf(split[i]));
       }
        Integer integer = service.updateUsers(id);
        if(integer>0){
            json=new Json(200,"成功");
        }else{
            json=new Json(400,"失败");
        }
        return json;
    }

    /**
     *
     * 根据id批量启用
     * @param ids
     * @return
     */
    @PreAuthorize("hasAuthority('user:management')")
    @DeleteMapping("/enabled")
    public Json enabled(String ids){
        System.out.println(ids);
        List<Integer> id=new ArrayList<>();
        String[] split = ids.split(",");
        for(int i=0;i<split.length;i++){
            id.add(Integer.valueOf(split[i]));
        }
        Integer enabled = service.enabled(id);
        if(enabled>0){
            json=new Json(200,"成功");
        }else{
            json=new Json(400,"失败");
        }
        return json;
    }

    /**
     *
     * 查询数据
     * @param curr  必须
     * @param size  必须
     * @param name
     * @param role
     * @param phone
     * @return
     */
    @PreAuthorize("hasAuthority('user:management')")
    @GetMapping("/selectUser")
    public Json selectUser( Integer curr,  Integer size, String name,String role,String phone,String startTime,String endTime,String sex,String email,String state){
        PageInfo info = service.selectUser(curr, size, name,role,phone,
                startTime==null?null:startTime+" 00:00:00",endTime==null?null:endTime+" 23:59:59"
        ,sex,email,state);
        json=new Json();
        json.setCode(200);
        json.setMsg("成功");
        json.setData(info.getList());
        json.setTotal((int)info.getTotal());
        return json;
    }
    //查询所有用户
    @PreAuthorize("hasAuthority('user:management')")
    @GetMapping("/selectAllUsers")
    public Json selectAllUsers(){
        List<User> users = service.selectAllUser();
        return Json.ok(users);
    }
    //查询用户总数
    @GetMapping("/selectUserByCount")
    public Json selectUserCount(){
        Long aLong = service.selectUserByCount();
        json=new Json();
        json.setCode(200);
        json.setTotal(Math.toIntExact(aLong));
        return json;
    }
    //查询今日新增用户数量
    @GetMapping("/NewUsersToday")
    public Json NewUsersToday(){
        Integer aLong = service.NewUsersToday();
        json=new Json();
        json.setTotal(aLong);
        return json;
    }
    //查询昨日新增用户数量
    @GetMapping("/YesterdayUsersToday")
    public Json YesterdayUsersToday(){
        Integer integer = service.YesterdayUsersToday();
        json=new Json();
        json.setTotal(integer);
        return json;
    }

    //查询本月注册用户数量
    @GetMapping("/monthTheRegistered")
    public Json monthTheRegistered(){
        Integer integer = service.monthTheRegistered();
        json=new Json();
        json.setTotal(integer);
        return json;
    }

    /**
     *
     * 将今日，昨日，本月，用户总数 写成一个方法，前端直接调用此方法就可获取到相应的数据
     * @return
     */
    @GetMapping("/queryUserOverviewData")
    public Json queryUserOverviewData(){
        Map<String, Integer> users = service.queryUserOverviewData();
        json=new Json();
        json.setData(users);
        return json;
    }

    //根据时间查询用户数量
    @GetMapping("/selectUserByTime")
    public Json selectUserByTime(String time){
        Integer integer = service.selectUserByTime(time);
        json=new Json();
        json.setTotal(integer);
        return json;
    }

    /**
     *
     * 根据id查询用户
     * @param userId
     * @return
     */
    @GetMapping("/getUserById/{userId}")
    public Json getUserById(@RequestBody @PathVariable Integer userId){
        User userById = service.getUserById(userId);
        json=new Json();
        if(null!=userById){
            json.setCode(200);
            json.setData(userById);
        }else {
            json.setCode(400);
        }
        return json;
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public Json logout(){
        //获取 hoder里面用户信息
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer userid = principal.getUser().getUserId();
        //删除redis 的值
        redisCache.deleteObject(LOGIN_USER_TOKEN+userid);
        log.info("-------------删除用户id为:"+userid+"的redis缓存-------------");
        return Json.ok("退出登录成功");
    }



}
